<template>
    <div style="text-align: center">
        <el-upload
            ref="upload"
            action
            :limit="1"
            :on-exceed="handleExceed"
            accept=".xlsx,.xls"
            :show-file-list="true"
            :auto-upload="false"
            :on-change="handelChange"
        >
            <el-button type="primary" style="margin: 30px auto">导入Excel</el-button>
        </el-upload>
    </div>
    <div v-if="isShow" class="tableList">
        <el-table :data="tableData" style="width: 80%; margin: auto">
            <el-table-column prop="name" label="Date" width="180" />
            <el-table-column prop="age" label="Name" width="180" />
        </el-table>
    </div>
</template>

<script setup>
// 实现文件覆盖上传显示
import { ref } from "vue";
import { genFileId } from "element-plus";
const upload = ref();
const handleExceed = (files) => {
    upload.value.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    upload.value.handleStart(file);
};
const submitUpload = () => {
    upload.value.submit();
};

// 定义数据初始化及列表显示控制
let tableData = ref([]);
let isShow = ref(false);
// 引入xlsx
import xlsx from "xlsx";
// 引入文件读取二进制获取数据的方法
import { readFile } from "@/vendor/utils";
// 定义异步方法解析文件
const handelChange = async (ev) => {
    // 获取EXCEL数据
    let file = ev.raw;
    if (!file) return;
    // 读取file中的数据的二进制
    let data = await readFile(file);
    // 用xlsx读取二进制数据
    let workbook = xlsx.read(data, { type: "binary" });
    // 获取解析后的数据
    workbook = workbook.Sheets[workbook.SheetNames[0]];
    // 使用工具转成每行一条的数组数据
    data = xlsx.utils.sheet_to_json(workbook);
    console.log(data);
    // 改变属性名，改成符合数据展示或后台需要的命名要求：可以继续添加
    const transformedData = data.map((item) => ({
        name: item.姓名,
        age: item.年龄,
    }));
    // 打印转换了属性名后的数据
    console.log(transformedData);
    // 给响应式变量赋值
    tableData.value = transformedData;
    // 控制列表显示
    isShow.value = true;
};
</script>

<style scoped>
.tableList {
    width: 800px;
    padding: 30px;
    background-color: aquamarine;
    margin: auto;
}
</style>
